package com.seisys.service.system.area;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.seisys.dao.DaoSupport;
import com.seisys.entity.Page;
import com.seisys.entity.system.Area;
import com.seisys.util.PageData;

@Service("areaService")
public class AreaService {

	@Resource(name = "daoSupport")
	private DaoSupport dao;

	/*
	 * 新增
	 */
	public void save(PageData pd) throws Exception {
		dao.save("AreaMapper.save", pd);
	}

	/*
	 * 删除
	 */
	public void delete(PageData pd) throws Exception {
		dao.delete("AreaMapper.delete", pd);
	}

	/*
	 * 修改
	 */
	public void edit(PageData pd) throws Exception {
		dao.update("AreaMapper.edit", pd);
	}

	/*
	 * 列表
	 */
	public List<PageData> list(Page page) throws Exception {
		return (List<PageData>) dao
				.findForList("AreaMapper.datalistPage", page);
	}

	/*
	 * 列表(全部)
	 */
	public List<PageData> listAll(PageData pd) throws Exception {
		return (List<PageData>) dao.findForList("AreaMapper.listAll", pd);
	}

	/*
	 * 通过id获取数据
	 */
	public PageData findById(PageData pd) throws Exception {
		return (PageData) dao.findForObject("AreaMapper.findById", pd);
	}

	/*
	 * 批量删除
	 */
	public void deleteAll(String[] ArrayDATA_IDS) throws Exception {
		dao.delete("AreaMapper.deleteAll", ArrayDATA_IDS);
	}

	public List<Area> findAllList() throws Exception {
		return (List<Area>) dao.findForList("AreaMapper.findAllList", "");
	}

	public List<Area> getAllParentArea() throws Exception {
		return (List<Area>) dao.findForList("AreaMapper.getAllParentArea", "");
	}

	public List<Area> listSubAreaByParentId(String parentId) throws Exception {
		return (List<Area>) dao.findForList("AreaMapper.listSubAreaByParentId",
				parentId);
	}

	public List<Area> listSubAreaById(String id) throws Exception {
		return (List<Area>) dao.findForList("AreaMapper.listSubAreaById", id);
	}

	public Area findAreaById(String id) throws Exception {
		return (Area) dao.findForObject("AreaMapper.findAreaById", id);
	}

	public List<Area> listAllArea() throws Exception {
		List<Area> rl = this.getAllParentArea();
		for (Area area : rl) {
			List<Area> subList = this.listSubAreaByParentId(area.getId());// 根据parentid==0的节点的id查找子节点
			if (subList.size() != 0) {
				subList = this.findSubArea(subList);
			}
			area.setAreaSub(subList);
		}
		return rl;

	}

	public List<Area> findSubArea(List<Area> of) throws Exception {
		for (Area triArea : of) {
			List<Area> triAreaList = new ArrayList<Area>();
			// String[] ary = triMenu.getPARENT_IDS().split(",");
			String triAreaID = triArea.getId();
			triAreaList = this.listSubAreaById(triAreaID);
			if (triAreaList.size() != 0) {
				triAreaList = this.findSubArea(triAreaList);
				triArea.setAreaSub(triAreaList);
			}
		}
		return of;
	}
}
